<template>
  <div class="systemPage-wrapper">
    <div class="topbar">
      <span class="icon iconfont iconxitongpingtai-biaojiegou"></span>
      <span>表结构</span>
      <div class="tabs">
        <span :class="activeTableProperty? 'active':''" @click="toTableProperty">表属性</span>
        <span :class="activeColumn? 'active':''" @click="toColumn">列</span>
        <span :class="activeSql? 'active':''" @click="toSql">sql语句</span>
      </div>
    </div>
    <div class="tableProperty-wrapper content-background">
      <table-list
          ref="pageMenu"
          class="tableList-wrapper"
          :selectShow="true"
          :menuitems="tableList"
          :activeitem="itemIndex"
          :dropmenus="dropMenu"
          @microIdss="microIdss"
          @menuitemss="menuitemss"
          @itemclick="tableItemclick"
          @add="add"
          @dropitemclick="dropMenuClick"
          @search="searchTable"
      ></table-list>
      <div class="right-board content-wrapper">
        <!-- 表属性 -->
        <el-form
            v-show="tableFormShow"
            class="newForm-wrapper systemForm"
            ref="form"
            :model="form"
            label-width="80px"
            labelPosition="left"
        >
          <el-form-item label="表名：" prop="name">
            <el-input v-model="form.name" class="systemInput" :disabled="tableOnlyRead"></el-input>
          </el-form-item>
          <el-form-item label="表编码：" prop="code">
            <el-input v-model="form.code" class="systemInput" :disabled="tableOnlyRead"></el-input>
          </el-form-item>
          <el-form-item label="表备注：" prop="code">
            <el-input v-model="form.note" class="systemInput" :disabled="tableOnlyRead"></el-input>
          </el-form-item>
          <!-- <el-form-item label="数据源：" prop="code">
            <el-select v-model="form.microId" placeholder="请选择" :disabled="tableOnlyRead">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item> -->
          <div class="buttons-wrapper" v-if="!tableOnlyRead">
            <span class="systemButtonCancel" @click="tableItemCancel">取消</span>
            <span class="systemButtonConfirm" @click="tableItemSave">保存</span>
          </div>
        </el-form>
        <!-- 列 -->
        <div class="column-wrapper content-wrapper" v-if="columnShow">
          <div class="searches-wrapper">
            <div class="buttons-wrapper">
              <span class="systemButtonDelete" @click="deleteColumn">删除</span>
              <span class="systemButtonAdd" @click="editOrAddColumn(-1)">新增</span>
              <span v-if="!columnEdit" class="systemButtonEdit" @click="editOrAddColumn()">编辑</span>
              <span v-if="columnEdit" class="systemButtonSaveIcon" @click="saveColumn()">保存</span>
              <span v-if="columnEdit" class="systemButtonCancelIcon" @click="cancelColumn()">取消</span>
            </div>
          </div>
          <el-table
              :highlight-current-row="true"
              class="systemTable"
              :data="columnList"
              stripe
              tooltip-effect="dark"
              style="width: 100%"
              height="calc(100% - 72px)"
              @selection-change="handleSelectionChange"
              :row-class-name="rowStyle"
          >
            <el-table-column
                type="selection"
                label-class-name="disabledSelection"
                width="80"
                header-align="center"
                align="center"
            ></el-table-column>
            <el-table-column prop="name" label="字段名" align="center" show-overflow-tooltip width="180">
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.name" placement="top-start" :disabled="!scope.row.name">
                  <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.name"></el-input>
                </el-tooltip>
              </template>
            </el-table-column>
<!--            <el-table-column prop="code" label="字段编码" align="center" show-overflow-tooltip width="120">-->
<!--              <template slot-scope="scope">-->
<!--                <el-tooltip :content="scope.row.code" placement="top-start" :disabled="!scope.row.code">-->
<!--                  <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.code"></el-input>-->
<!--                </el-tooltip>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column prop="datatype" label="数据类型" align="center" show-overflow-tooltip width="120">
              <template slot-scope="scope">
                <el-select :disabled="isEditObj[scope.$index].a" v-model="scope.row.datatype">
                  <el-option v-for="item in dataTypeMap" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="length" label="字段长度" align="center" show-overflow-tooltip width="80">
              <template slot-scope="scope">
                <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.length"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="precision" label="字段精度" align="center" show-overflow-tooltip width="80">
              <template slot-scope="scope">
                <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.precision"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="primary" label="是否主键" align="center" show-overflow-tooltip width="80">
              <template slot-scope="scope">
                <el-select :disabled="isEditObj[scope.$index].a" v-model="scope.row.primary">
                  <el-option
                      v-for="item in primaryMap"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  ></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column prop="note" label="备注" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <el-tooltip :content="scope.row.note" placement="top-start" :disabled="!scope.row.note">
                  <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.note"></el-input>
                </el-tooltip>
              </template>
            </el-table-column>
<!--            <el-table-column prop="imp_primary" label="是否导入主键" align="center" show-overflow-tooltip width="120">-->
<!--              <template slot-scope="scope">-->
<!--                <el-select :disabled="isEditObj[scope.$index].a" v-model="scope.row.imp_primary">-->
<!--                  <el-option-->
<!--                      v-for="item in selectMap"-->
<!--                      :key="item.value"-->
<!--                      :label="item.label"-->
<!--                      :value="item.value"-->
<!--                  ></el-option>-->
<!--                </el-select>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="imp_virtual" label="是否虚拟字段" align="center" show-overflow-tooltip width="120">-->
<!--              <template slot-scope="scope">-->
<!--                <el-select :disabled="isEditObj[scope.$index].a" v-model="scope.row.imp_virtual">-->
<!--                  <el-option-->
<!--                      v-for="item in selectMap"-->
<!--                      :key="item.value"-->
<!--                      :label="item.label"-->
<!--                      :value="item.value"-->
<!--                  ></el-option>-->
<!--                </el-select>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="imp_null" label="是否可为空" align="center" show-overflow-tooltip width="100">-->
<!--              <template slot-scope="scope">-->
<!--                <el-select :disabled="isEditObj[scope.$index].a" v-model="scope.row.imp_null">-->
<!--                  <el-option-->
<!--                      v-for="item in selectMap"-->
<!--                      :key="item.value"-->
<!--                      :label="item.label"-->
<!--                      :value="item.value"-->
<!--                  ></el-option>-->
<!--                </el-select>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="imp_same_name" label="是否存在同名列" align="center" show-overflow-tooltip width="120">-->
<!--              <template slot-scope="scope">-->
<!--                <el-select :disabled="isEditObj[scope.$index].a" v-model="scope.row.imp_same_name">-->
<!--                  <el-option-->
<!--                      v-for="item in selectMap"-->
<!--                      :key="item.value"-->
<!--                      :label="item.label"-->
<!--                      :value="item.value"-->
<!--                  ></el-option>-->
<!--                </el-select>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="enable_imp" label="是否启用导入" align="center" show-overflow-tooltip width="120">-->
<!--              <template slot-scope="scope">-->
<!--                <el-select :disabled="isEditObj[scope.$index].a" v-model="scope.row.enable_imp">-->
<!--                  <el-option-->
<!--                      v-for="item in selectMap"-->
<!--                      :key="item.value"-->
<!--                      :label="item.label"-->
<!--                      :value="item.value"-->
<!--                  ></el-option>-->
<!--                </el-select>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="imp_column_num" label="列号" align="center" show-overflow-tooltip width="80">-->
<!--              <template slot-scope="scope">-->
<!--                <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.imp_column_num"></el-input>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="imp_sql" label="外键键值转换" align="center" show-overflow-tooltip width="120">-->
<!--              <template slot-scope="scope">-->
<!--                <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.imp_sql"></el-input>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="imp_regex" label="正则表达式" align="center" show-overflow-tooltip width="100">-->
<!--              <template slot-scope="scope">-->
<!--                <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.imp_regex"></el-input>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="imp_default" label="默认值" align="center" show-overflow-tooltip width="80">-->
<!--              <template slot-scope="scope">-->
<!--                <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.imp_default"></el-input>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--            <el-table-column prop="imp_custom" label="自定义" align="center" show-overflow-tooltip width="80">-->
<!--              <template slot-scope="scope">-->
<!--                <el-input :disabled="isEditObj[scope.$index].a" v-model="scope.row.imp_custom"></el-input>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <!--            <el-table-column prop="operation" label="操作" align="center" show-overflow-tooltip>-->
            <!--              <template slot-scope="scope">-->
            <!--                <div v-show="isEditObj[scope.$index].a" class="operation">-->
            <!--                  <span @click="editOrAddColumn(scope.$index)">编辑</span>-->
            <!--                </div>-->
            <!--                <div v-show="!isEditObj[scope.$index].a" class="operation">-->
            <!--                  <span @click="saveColumn(scope.$index)">保存</span>-->
            <!--                  <span style="margin-left: 5px;" @click="cancelColumn(scope.$index)">取消</span>-->
            <!--                </div>-->
            <!--              </template>-->
            <!--            </el-table-column>-->
          </el-table>
        </div>
        <!-- sql -->
        <div class="sql-wrapper" v-if="sqlShow">
          <span v-for="(item,i) in sql" :key="i">{{ item }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import TableList from '@/system/components/pageMenu'
import {
  tableList,
  tableSave,
  tableDelete,
  columnList,
  saveColumn,
  deleteColumn,
  createSQL,
  getDataTypeMap,
  dataOriginAll
} from '@/system/api/listStructure'

export default {
  name: 'listStructure',
  data() {
    return {
      options: [],
      activeTableProperty: true,
      activeColumn: false,
      activeSql: false,

      tableList: [],
      itemIndex: -1,
      searchValue: '',

      tableFormShow: false,
      tableOnlyRead: true,
      form: {
        name: '',
        code: '',
        microId: ''
      },
      newMicroId: 1,
      columnShow: false,
      columnList: [],
      columnEdit: false,
      isEditObj: [],
      currentItems: [],
      dataTypeMap: [],
      primaryMap: [
        {value: false, label: '否'},
        {value: true, label: '是'},
      ],
      selectMap: [
        {value: 1, label: '是'},
        {value: 0, label: '否'},
      ],
      sqlShow: false,
      sql: [],
      dropMenu: [
        {
          name: '编辑',
          iconPosition: 'before',
          iconname: 'delicon',
        },
        {
          name: '删除',
          iconPosition: 'before',
          iconname: 'delicon',
        },
      ],

      multipleSelection: []

    }
  },
  components: {
    TableList,
  },
  watch: {
    columnList(val) {
      this.isEditObj = []
      for (let i in val) {
        let a = i
        this.isEditObj.push({
          a: true,
        })
      }
    },
  },
  created() {
    this.dataOriginAll()
    this.tableInitialization(-1)
    this.tableFormShow = true
    getDataTypeMap({name: '数据类型'}).then((res) => {
      if (res.success) {
        this.dataTypeMap = JSON.parse(JSON.stringify(res.info))
      } else this.message(res.msg, 3)
    })
  },
  methods: {
    // 表单微服务查询
    menuitemss(e){
      this.tableList = e
    },
    // 微服务查询
    async dataOriginAll() {
      const originAll = await dataOriginAll()
      if(originAll.success){
        originAll.info.map(item =>{
          this.options.push(item)
        })
        console.log('aaaaaa',this.options);
      }else{
        this.$message('获取微服务失败')
      }
      
    },
    // tab切换
    toTableProperty() {
      this.tabInitialization()
      this.tableFormShow = true
      this.activeTableProperty = true
    },
    toColumn() {
      if (!this.form.id && !this.tableOnlyRead) {
        this.message('请先保存新增的表', 3)
        return
      } else {
        this.tabInitialization()
        this.columnInitialization(this.form.id)
        this.columnShow = true
        this.activeColumn = true
      }
    },
    toSql() {
      if (!this.form.id && !this.tableOnlyRead) {
        this.message('请先保存新增的表', 3)
        return
      } else {
        this.tabInitialization()
        this.sqlShow = true
        this.activeSql = true
        createSQL({id: this.form.id}).then((res) => {
          if (res.success) {
            this.sql = res.info
          } else this.message(res.msg, 3)
        })
      }
    },
    tabInitialization() {
      this.tableFormShow = false
      this.columnShow = false
      this.sqlShow = false
      this.activeTableProperty = false
      this.activeColumn = false
      this.activeSql = false
      this.currentItems = []
      this.columnEdit = false
    },
    // 表初始化
    tableInitialization(index) {
      tableList({keyword: this.searchValue, microId: this.newMicroId}).then((res) => {
        if (res.success) {
          this.tableList = JSON.parse(JSON.stringify(res.info))
          if (index === -1) {
            this.tableOnlyRead = true
            this.form = {}
            this.itemIndex = -1
          } else {
            this.form = this.tableList[index]
          }
        } else this.message(res.msg, 3)
      })
    },
    // 表查询
    searchTable(e) {
      this.searchValue = e
      this.tableInitialization(-1)
    },
    // 表点击
    tableItemclick(e, index) {
      this.columnEdit = false
      this.tableOnlyRead = true
      this.form = JSON.parse(JSON.stringify(e))
      this.itemIndex = index
      if (this.activeTableProperty) {
        this.toTableProperty()
      } else if (this.activeColumn) {
        this.toColumn()
      } else {
        this.toSql()
      }
    },
    // 表新增
    add() {
      this.tabInitialization()
      this.tableOnlyRead = false
      this.tableFormShow = true
      this.form = {}
      this.itemIndex = -1
      this.activeTableProperty = true
    },
    // 表编辑&删除
    dropMenuClick(item, button, type) {
      for (let i = 0; i < this.tableList.length; i++) {
        if (item.id === this.tableList[i].id) {
          this.itemIndex = i
        }
      }
      if (type) {
        this.messageBox('确认删除？').then((c) => {
          if (c.action) {
            tableDelete({id: item.id}).then((res) => {
              if (res.success) {
                this.message(res.msg, 1)
                this.toTableProperty()
                this.tableInitialization(-1)
              } else {
                this.message(res.msg, 3)
                return
              }
            })
          }
        })
      } else {
        this.toTableProperty()
        this.form = JSON.parse(JSON.stringify(item))
        this.tableOnlyRead = false
      }
    },
    // 表保存
    tableItemSave() {
      if (!this.form.name) {
        this.message('请输入表名', 3)
        return false
      } else {
        this.form.microId = this.newMicroId
        tableSave(this.form).then((res) => {
          // 新增保存
          if (res.success) {
            this.tableOnlyRead = true
            if (this.itemIndex == -1) {
              this.itemIndex = this.tableList.length
              this.tableInitialization(this.itemIndex)
              this.form = res.info
              this.$refs.pageMenu.scrollPage()
            } else {
              this.tableInitialization(this.itemIndex)
            }
            this.message(res.msg, 1)
          } else this.message(res.msg, 3)
        })
      }
    },
    // 表取消
    tableItemCancel() {
      this.tableOnlyRead = true
      this.tableInitialization(this.itemIndex)
    },
    // 列初始化
    columnInitialization(id) {
      columnList({tid: id}).then((res) => {
        if (res.success) {
          this.columnList = JSON.parse(JSON.stringify(res.info))
        } else this.message(res.msg, 3)
      })
    },
    // 列新增&编辑
    editOrAddColumn(index) {
      if (!this.form.id) {
        this.message('请先选择表', 3)
        return
      }
      for (let i = 0; i < this.columnList.length; i++) {
        if (this.isEditObj[i].a === false) {
          this.message('请先保存正在编辑的字段', 3)
          return
        }
      }
      // 新增
      if (index == -1) {
        let newColumn = {
          name: '',
          code: '',
          datatype: '',
          length: '',
          note: '',
          precision: '',
          primary: false,
          tid: this.form.id, // 表 ID
          imp_primary: 0,
          imp_virtual: 0,
          imp_null: 1,
          imp_same_name: 0,
          enable_imp: 1,
          imp_column_num: 0,
          imp_sql: '',
          imp_regex: '',
          imp_default: '',
          imp_custom: '',
        }
        this.columnList.push(newColumn)
        setTimeout(() => {
          this.isEditObj[this.columnList.length - 1].a = false
        }, 200)
      } else {
        // 编辑
        if (this.currentItems.length === 0) {
          this.message('请勾选需要编辑的数据', 3)
          return
        }
        if (this.currentItems.length > 1) {
          this.message('不能编辑多条数据', 3)
          return
        }
        this.isEditObj[this.multipleSelection].a = false
      }
      this.columnEdit = true
    },
    // 列保存
    saveColumn() {
      const index = this.columnList[this.columnList.length - 1].id ? this.multipleSelection : this.columnList.length - 1
      if (!this.isRealNum(this.columnList[index].length)) {
        this.message('字段长度只能为数字', 3)
        this.isEditObj[index].a = false
        return
      }
      if (!this.isRealNum(this.columnList[index].precision)) {
        this.message('字段精度只能为数字', 3)
        this.isEditObj[index].a = false
        return
      }
      saveColumn(this.columnList[index]).then((res) => {
        if (res.success) {
          this.message(res.msg, 1)
          this.columnInitialization(this.form.id)
          this.columnEdit = false
        } else {
          this.message(res.msg, 3)
          this.isEditObj[index].a = false
        }
      })
    },
    isRealNum(val) {
      if (!isNaN(val)) {
        return true
      } else {
        return false
      }
    },
    // 列取消
    cancelColumn() {
      if (!this.columnList[this.columnList.length - 1].id) { // 新增取消
        this.columnList.pop()
        this.isEditObj.pop()
      } else { // 编辑取消
        this.isEditObj[this.multipleSelection].a = true
        this.columnInitialization(this.form.id)
      }
      this.columnEdit = false
    },
    // 列勾选
    handleSelectionChange(e) {
      this.currentItems = []
      for (let i = 0; i < e.length; i++) {
        let id = JSON.parse(JSON.stringify(e[i].id))
        this.currentItems.push(id)
      }
      // 记录行索引，设置样式
      let arr = [];
      e.forEach((val) => {
        this.columnList.forEach((v, i) => {
          if (val.id == v.id) {
            arr.push(i)
          }
        })
      })
      this.multipleSelection = arr;
    },
    rowStyle(row) {
      let arr = this.multipleSelection
      const rowIndex = row.rowIndex
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === rowIndex) {
          return 'checkedRow'
        }
      }
    },
    // 列删除
    deleteColumn() {
      if (!this.form.id) {
        this.message('请先选择表', 3)
        return
      }
      if (!this.currentItems.length) {
        this.message('请选择需要删除的字段', 3)
      } else {
        this.messageBox('确认删除？').then((c) => {
          if (c.action) {
            deleteColumn({id: String(this.currentItems)}).then(
                (res) => {
                  if (res.success) {
                    this.message(res.msg, 1)
                    this.columnInitialization(this.form.id)
                  } else this.message(res.msg, 3)
                }
            )
          }
        })
      }
    },
    microIdss(num){
      this.newMicroId = num
    }
  },
}
</script>

<style lang="scss" scoped>
.systemPage-wrapper {
  .topbar {
    position: relative;

    .tabs {
      position: absolute;
      right: 0px;

      span {
        width: 96px;
        height: 32px;
        line-height: 32px;
        border-radius: 4px;
        display: inline-block;
        margin-right: 12px;
        border: 1px solid rgba(83, 167, 255, 1);
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: var(--organization-tabs-text-color);
        cursor: pointer;

        &:hover,
        &.active {
          background: rgba(81, 167, 253, 1);
          box-shadow: 0px 3px 6px 0px rgba(0, 57, 151, 0.1);
          font-weight: bold;
          color: rgba(255, 255, 255, 1);
        }

        &:hover {
          opacity: 0.6;
        }

        &:active {
          opacity: 1;
        }
      }
    }
  }

  .tableProperty-wrapper {
    display: flex;
    overflow: hidden;

    .tableList-wrapper {
      height: 100%;
      width: 234px;
    }

    .right-board {
      width: calc(100% - 246px);
      margin-left: 12px;
      overflow: hidden;

      .newForm-wrapper {
        margin: 29px 30px;
        position: relative;

        .el-form-item {
          padding: 0;
          margin-bottom: 12px;
          height: 32px;
          display: flex;
          align-items: center;

          ::v-deep.el-form-item__content {
            width: 100%;
            margin-left: 0 !important;
          }
        }

        .buttons-wrapper {
          position: absolute;
          right: 0;
          bottom: -50px;
          display: flex;
          flex-direction: row;

          .systemButtonConfirm {
            margin-left: 20px;
          }
        }
      }

      .column-wrapper {
        ::v-deep.cell {
          width: 100% !important;

          .el-input.is-disabled input {
            border: none !important;
            background-color: transparent;
            text-align: center;
          }
        }
      }

      .sql-wrapper {
        text-align: left;
        padding: 10px;
        overflow: auto;

        span {
          color: var(--system-page-topbar-text-color);
          display: block;
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style>
